<template>
  <div class="app-container video-split-view">
    <div class="split-view-container">
      <!-- 左侧设备列表 -->
      <div class="channel-list-panel">
        <div class="panel-header">
          <span class="panel-title">设备列表</span>
        </div>
        <div class="panel-content">
          <!-- 设备列表上方的操作引导 -->
          <div class="operation-guide" v-if="selectedPanel === -1">
            <el-alert
              title="请先点击右侧视频面板，再从列表中选择设备"
              type="info"
              :closable="false"
              show-icon>
            </el-alert>
          </div>
          <div class="operation-guide" v-else>
            <el-alert
              :title="'请选择设备加载到面板 ' + (selectedPanel + 1)"
              type="success"
              :closable="false"
              show-icon>
            </el-alert>
          </div>

          <el-tree
            class="device-tree"
            :props="treeProps"
            :load="loadNode"
            lazy
            @node-click="handleNodeClick"
            v-loading="treeLoading"
            highlight-current
            :expand-on-click-node="false"
          >
            <span class="custom-tree-node" slot-scope="{ node, data }">
              <span><i :class="data.icon" style="margin-right: 4px;"></i>{{ node.label }}</span>
            </span>
          </el-tree>
        </div>
      </div>

      <!-- 右侧视频区域 -->
      <div class="video-view-panel">
        <!-- 顶部控制栏 -->
        <div class="control-panel">
          <div class="left-controls">
            <el-button-group>
              <el-tooltip content="1分屏" placement="top">
                <el-button :type="layout === 1 ? 'primary' : 'default'" icon="el-icon-menu" @click="changeLayout(1)"></el-button>
              </el-tooltip>
              <el-tooltip content="4分屏" placement="top">
                <el-button :type="layout === 4 ? 'primary' : 'default'" icon="el-icon-s-grid" @click="changeLayout(4)"></el-button>
              </el-tooltip>
              <el-tooltip content="9分屏" placement="top">
                <el-button :type="layout === 9 ? 'primary' : 'default'" icon="el-icon-menu" @click="changeLayout(9)"></el-button>
              </el-tooltip>
              <el-tooltip content="16分屏" placement="top">
                <el-button :type="layout === 16 ? 'primary' : 'default'" icon="el-icon-s-fold" @click="changeLayout(16)"></el-button>
              </el-tooltip>
            </el-button-group>
          </div>
          <div class="right-controls">
            <el-tooltip content="全屏" placement="top">
              <el-button icon="el-icon-full-screen" @click="toggleFullscreen"></el-button>
            </el-tooltip>
            <el-tooltip content="刷新所有" placement="top">
              <el-button icon="el-icon-refresh" @click="refreshAllVideos"></el-button>
            </el-tooltip>
          </div>
        </div>

        <!-- 视频区域 -->
        <div class="video-container" ref="videoContainer" :class="'layout-' + layout">
          <div v-for="n in layout" :key="n" class="video-panel" :class="{'active': selectedPanel === n-1}" @click="selectPanel(n-1)">
            <!-- 右上角删除按钮 -->
            <div v-if="panels[n-1].streamUrl" class="panel-close-btn" @click.stop="closeVideo(n-1)">
              <el-tooltip content="删除监控" placement="top">
                <i class="el-icon-close"></i>
              </el-tooltip>
            </div>

            <div class="video-wrapper" v-loading="panels[n-1].loading">
              <!-- 使用devicePlayer组件替换iframe -->
              <device-player v-if="panels[n-1].streamUrl"
                             :ref="'player-' + (n-1)"
                             :videoUrl="panels[n-1].streamUrl"
                             :height="'100%'"
                             :autoplay="true"
                             :live="true"
                             :is-dialog="false"
                             :show-ptz="false"
                             :show-tabs="false"
                             :show-toolbar="false">
              </device-player>

              <!-- 空面板时显示的内容 -->
              <div v-if="!panels[n-1].streamUrl" class="empty-panel">
                <i class="el-icon-video-camera-solid"></i>
                <p v-if="selectedPanel === n-1">已选中此面板，请在左侧选择设备</p>
                <p v-else>点击选择此面板</p>
              </div>
            </div>

            <!-- 面板标题 -->
            <div class="panel-info">
              <span class="panel-title">{{ panels[n-1].title || '未选择设备' }}</span>
              <div class="panel-controls" v-if="panels[n-1].streamUrl">
                <el-tooltip content="关闭" placement="top">
                  <i class="el-icon-close" @click.stop="closeVideo(n-1)"></i>
                </el-tooltip>
              </div>
              <div class="panel-number">{{ n }}</div>
            </div>

            <!-- 面板详细信息 -->
            <div class="panel-detail" v-if="panels[n-1].channel">
              <span class="detail-item">{{ panels[n-1].channel.manufacturer }} {{ panels[n-1].channel.model }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getWvpDeviceChannel, listWvpDeviceChannel } from "@/api/system/wvpDeviceChannel";
import { getWvpDevice, listWvpDevice } from "@/api/system/wvpDevice";
import { listDeviceInfo } from "@/api/system/deviceInfo";
import { wvpLogin, startPlay as wvpStartPlay } from "@/utils/wvpRequest";
import devicePlayer from "@/components/DevicePlayer";

export default {
  name: "SplitView",
  components: { devicePlayer },
  data() {
    return {
      // 布局类型：1、4、9、16
      layout: 4,
      // 已选面板
      selectedPanel: -1,
      // 各面板数据
      panels: Array.from({ length: 16 }, () => ({
        loading: false,
        streamUrl: '',
        channel: null,
        title: '',
        player: null
      })),
      // 表格加载状态
      tableLoading: false,
      // 设备列表
      deviceList: [],
      // 查询参数 - 修改为一次性获取1000个通道
      queryParams: {
        pageNum: 1,
        pageSize: 1000
      },
      // WVP登录状态
      isWvpLoggedIn: false,
      // WVP token信息
      wvpAccessToken: null,
      // 树形结构相关
      treeProps: {
        label: 'deviceName',
        children: 'children',
        isLeaf: 'isLeaf',
        disabled: 'disabled'
      },
      treeLoading: false,
    };
  },
  created() {
    // 初始化时自动登录WVP平台
    this.loginToWvp();
    // 初始化时获取设备列表
    this.getDeviceList();
  },
  mounted() {
    // 监听窗口大小变化，调整布局
    window.addEventListener('resize', this.handleResize);
  },
  beforeDestroy() {
    // 组件销毁前关闭所有视频流并移除事件监听
    window.removeEventListener('resize', this.handleResize);
    this.cleanupAllVideos();
  },
  methods: {
    // 自动登录WVP平台
    loginToWvp() {
      console.log("========== 开始登录WVP视频平台 ==========");

      // 如果已登录，则不重复登录
      if (this.isWvpLoggedIn && this.wvpAccessToken) {
        console.log("✓ WVP平台已经登录，无需重复登录");
        console.log("当前AccessToken:", this.wvpAccessToken.substring(0, 15) + "...");
        return Promise.resolve(this.wvpAccessToken);
      }

      console.log("⌚ 正在向WVP平台发送登录请求...");

      // 使用封装的WVP请求工具进行登录
      return wvpLogin('admin', '6f1db4f72b187835d9ac5068223ad822')
        .then(res => {
          console.log("收到WVP登录响应:", res);

          if (res && res.code === 0 && res.data && res.data.accessToken) {
            this.wvpAccessToken = res.data.accessToken;
            this.isWvpLoggedIn = true;
            console.log("✅ WVP-GB28181-Pro登录成功");
            console.log("AccessToken前15位:", this.wvpAccessToken.substring(0, 15) + "...");
            this.$message.success("视频平台连接成功");
            console.log("========== WVP平台登录完成 ==========");
            return this.wvpAccessToken;
          } else {
            console.error("【错误】WVP平台登录失败，响应不包含有效的accessToken");
            console.error("响应内容:", res);
            this.$message.error("视频平台连接失败: 未获取到访问令牌");
            console.log("========== WVP平台登录失败 ==========");
            throw new Error(res && res.msg ? res.msg : "登录失败，未获取到访问令牌");
          }
        })
        .catch(err => {
          console.error("【错误】WVP平台登录请求异常:", err);
          console.error("错误信息:", err.message || "未知错误");

          if (err.response) {
            console.error("响应状态:", err.response.status);
            console.error("响应数据:", err.response.data);
          }

          this.$message.error("连接视频平台失败: " + (err.message || "未知错误"));
          console.log("========== WVP平台登录失败 ==========");
          throw err;
        });
    },
    // 切换布局
    changeLayout(newLayout) {
      // 深拷贝当前视频流数据，以保留所有状态
      const currentPanels = JSON.parse(JSON.stringify(this.panels));

      // 停止所有当前视频流，但不清除数据
      this.stopAllVideoPlayers();

      // 更新布局
      this.layout = newLayout;
      this.selectedPanel = -1;

      // 如果旧布局中有视频，重新加载
      this.$nextTick(() => {
        // 只加载新布局能容纳的视频面板
        for (let i = 0; i < Math.min(newLayout, currentPanels.length); i++) {
          if (currentPanels[i].channel) {
            // 恢复面板的channel和title信息
            this.panels[i].channel = currentPanels[i].channel;
            this.panels[i].title = currentPanels[i].title;

            // 重新加载视频流
            this.loadVideoToPanel(currentPanels[i].channel, i);
          }
        }
      });
    },

    // 选择面板
    selectPanel(index) {
      // 选中面板，突出显示
      this.selectedPanel = index;

      // 提示用户
      this.$message({
        message: `已选中面板 ${index + 1}，请在左侧列表选择设备`,
        type: 'success',
        duration: 2000
      });
    },

    // 查询设备列表，用于树的根节点
    getDeviceList() {
      this.treeLoading = true;
      listDeviceInfo({ pageNum: 1, pageSize: 1000 }).then(response => {
        // 过滤出具有国标ID的设备
        this.deviceList = response.rows.filter(item => {
          return item.wvpDeviceId && item.wvpDeviceId.trim() !== '';
        }).map(item => ({
          // 树节点数据
          ...item,
          isLeaf: false, // 设备节点，非叶子
          icon: 'el-icon-monitor'
        }));
        console.log("获取到根设备节点列表:", this.deviceList);
        this.treeLoading = false;
        // 注意：这里我们不再直接将数据赋给树，因为我们使用了懒加载。
        // lazy load 会自动调用 loadNode 来获取根节点。
      }).catch(error => {
        this.treeLoading = false;
        console.error("获取设备列表失败:", error);
        this.$message.error("获取设备列表失败");
      });
    },

    // 懒加载树节点
    async loadNode(node, resolve) {
      console.log(`========== 开始加载树节点 (层级: ${node.level}) ==========`);
      // 加载根节点 (IoT设备)
      if (node.level === 0) {
        this.treeLoading = true;
        try {
          const response = await listDeviceInfo({ pageNum: 1, pageSize: 1000 });
          const rootNodes = response.rows.filter(item => item.wvpDeviceId && item.wvpDeviceId.trim() !== '').map(item => ({
            ...item,
            deviceName: `${item.deviceName} --- ${item.wvpDeviceId}`, // 修改设备节点显示名称
            isLeaf: false,
            icon: 'el-icon-monitor',
          }));
          console.log(`✅ 成功加载 ${rootNodes.length} 个根设备节点`);
          this.treeLoading = false;
          return resolve(rootNodes);
        } catch (error) {
          console.error("【错误】加载根设备节点失败:", error);
          this.$message.error("加载设备列表失败");
          this.treeLoading = false;
          return resolve([]);
        }
      }

      // 加载子节点 (通道)
      if (node.level === 1) {
        const iotDevice = node.data;
        console.log(`尝试加载设备 [${iotDevice.deviceName}] 的子通道...`);
        console.log("【父设备信息】", iotDevice);

        try {
          // 1. 使用IoT设备的wvp_device_id查询WVP设备信息
          console.log(`1. 查询WVP设备，使用IoT.wvpDeviceId: ${iotDevice.wvpDeviceId}`);
          const gbDevice = await this.getWvpDeviceInfo(iotDevice.wvpDeviceId);

          if (!gbDevice || !gbDevice.id) {
            console.warn(`【警告】未找到对应的WVP设备或设备无主键ID，无法加载通道。`);
            return resolve([]);
          }
          console.log(`✅ 找到WVP设备，主键ID: ${gbDevice.id}`);

          // 2. 使用WVP设备的主键id查询其下的所有通道
          console.log(`2. 查询WVP通道，使用WVP设备ID: ${gbDevice.id}`);
          const channels = await this.getWvpChannelsByDeviceId(gbDevice.id);

          if (!channels || channels.length === 0) {
            console.log(`设备 [${iotDevice.deviceName}] 下无通道。`);
            return resolve([]);
          }
          console.log(`✅ 找到 ${channels.length} 个通道`);

          const channelNodes = channels.map(c => ({
            ...c,
            deviceName: `${c.name || '未命名通道'} --- ${c.deviceId}`, // 按要求显示
            isLeaf: true, // 通道是叶子节点
            icon: 'el-icon-camera-solid',
            parentWvpDeviceId: iotDevice.wvpDeviceId // 将父设备的国标ID存下来
          }));

          return resolve(channelNodes);

        } catch (error) {
          console.error(`【错误】加载设备 [${iotDevice.deviceName}] 的通道失败:`, error);
          // 不再弹出错误提示，而是显示一个友好的"暂无通道"节点
          const errorNode = [{
            deviceName: '暂无通道',
            isLeaf: true,
            icon: 'el-icon-folder-opened',
            disabled: true
          }];
          return resolve(errorNode);
        }
      }
      // 更深层级的节点不处理
      return resolve([]);
    },

    // 点击树节点
    handleNodeClick(data, node) {
      // 如果点击的不是叶子节点(通道)或节点被禁用，则不执行播放操作
      if (!node.isLeaf || data.disabled) {
        if (data.disabled) {
          console.log(`点击了被禁用的节点: [${data.deviceName}]`);
        } else {
          console.log(`点击了设备节点 [${data.deviceName}]，展开/折叠其子节点。`);
        }
        return;
      }

      console.clear();
      console.log("======================= 通道点击播放完整流程日志 =======================");
      const channel = data;
      const deviceName = node.parent.data.deviceName;
      console.log(`【点击目标】通道: [${channel.name}]`, channel);
      console.log(`【所属设备】设备: [${deviceName}]`, node.parent.data);

      if (this.selectedPanel < 0) {
        this.$message.warning("请先点击右侧视频面板选择一个位置");
        console.log("【流程终止】原因: 未选择任何视频面板。");
        return;
      }

      // 构造播放所需的参数
      const playData = {
        deviceName: deviceName, // 父设备名称
        channelName: channel.name, // 通道名称
        wvpDeviceId: channel.parentWvpDeviceId, // 父设备的国标ID
        wvpDeviceChannelId: channel.deviceId, // 通道的国标ID
        channel: channel // 完整的通道信息
      };

      console.log("【播放准备】");
      console.log("⌚ 即将停止现有视频播放器并加载新视频...");
      this.stopVideoPlayer(this.selectedPanel);

      console.log("最终构造的播放参数:", playData);

      this.loadVideoToPanel(playData, this.selectedPanel);
    },

    // 加载视频到面板
    loadVideoToPanel(channel, panelIndex) {
      console.log(`========== 开始加载视频到面板${panelIndex + 1} ==========`);

      if (!channel || !channel.wvpDeviceChannelId) {
        console.error(`【错误】通道信息不完整，无法加载视频`);
        console.error(`通道对象:`, channel);
        return;
      }

      console.log(`开始为设备 ${channel.deviceName} 的通道 ${channel.channelName || channel.wvpDeviceChannelId} 加载视频...`);

      // 获取面板对象
      const panel = this.panels[panelIndex];
      panel.loading = true;
      panel.title = channel.deviceName + (channel.channelName ? ` - ${channel.channelName}` : '');
      panel.channel = channel.channel; // 保存通道信息

      // 确保通道信息包含设备ID和通道ID
      if (!channel.wvpDeviceId || !channel.wvpDeviceChannelId) {
        console.error(`【错误】通道信息缺少设备ID或通道ID`);
        console.error(`设备ID: ${channel.wvpDeviceId}, 通道ID: ${channel.wvpDeviceChannelId}`);
        panel.loading = false;
        this.$message.error('通道信息不完整，无法播放视频');
        return;
      }

      // 检查WVP登录状态并处理视频加载
      if (!this.isWvpLoggedIn || !this.wvpAccessToken) {
        console.log("⚠ 检测到WVP平台未登录，尝试自动登录后加载视频...");

      // 先尝试登录WVP平台
        this.loginToWvp()
          .then(() => {
            console.log("✅ WVP平台登录成功，继续加载视频");
            // 传递完整对象，包含设备ID和通道ID
            const enrichedChannel = {
              ...channel,
              deviceId: channel.wvpDeviceId, // 确保deviceId字段存在
              channelId: channel.wvpDeviceChannelId // 确保channelId字段存在
            };
            this.doLoadVideo(enrichedChannel, panelIndex, panel);
          })
          .catch(err => {
            console.error("【严重错误】WVP平台登录失败，无法加载视频:", err);
            panel.loading = false;
            this.$message.error("连接视频平台失败，无法加载视频");
            console.log(`========== 视频加载失败(登录失败) ==========`);
          });
      } else {
        console.log("✅ WVP平台已登录，直接加载视频");
        // 传递完整对象，包含设备ID和通道ID
        const enrichedChannel = {
          ...channel,
          deviceId: channel.wvpDeviceId, // 确保deviceId字段存在
          channelId: channel.wvpDeviceChannelId // 确保channelId字段存在
        };
        this.doLoadVideo(enrichedChannel, panelIndex, panel);
      }
    },

    // 只停止视频播放，但保留通道信息
    stopVideoPlayer(panelIndex) {
      if (panelIndex < 0 || panelIndex >= this.panels.length) return;

      const panel = this.panels[panelIndex];
      const playerRef = this.$refs[`player-${panelIndex}`];

      // 如果播放器实例存在，则调用其销毁方法
      if (playerRef && playerRef[0] && typeof playerRef[0].close === 'function') {
        playerRef[0].close();
      }

      // 重置视频相关数据，但保留通道信息
      panel.streamUrl = '';
      panel.loading = false;
      panel.player = null; // 确保播放器引用被清除
    },

    // 完全清除视频，包括通道信息
    closeVideo(panelIndex) {
      if (panelIndex < 0 || panelIndex >= this.panels.length) return;

      // 先停止播放
      this.stopVideoPlayer(panelIndex);

      // 然后清除通道信息
      const panel = this.panels[panelIndex];
      panel.channel = null;
      panel.title = '';
    },

    // 停止所有视频播放，但保留通道信息
    stopAllVideoPlayers() {
      for (let i = 0; i < this.panels.length; i++) {
        this.stopVideoPlayer(i);
      }
    },

    // 完全清除所有视频，包括通道信息
    cleanupAllVideos() {
      for (let i = 0; i < this.panels.length; i++) {
        this.closeVideo(i);
      }
      this.selectedPanel = -1;
    },

    // 刷新所有视频
    refreshAllVideos() {
      for (let i = 0; i < this.layout; i++) {
        if (this.panels[i].channel) {
          const channel = this.panels[i].channel;
          this.stopVideoPlayer(i);
          this.loadVideoToPanel(channel, i);
        }
      }
    },

    // 切换全屏
    toggleFullscreen() {
      const container = this.$refs.videoContainer;

      if (!document.fullscreenElement) {
        // 使用更兼容的方式请求全屏
        if (container.requestFullscreen) {
          container.requestFullscreen();
        } else if (container.mozRequestFullScreen) { // Firefox
          container.mozRequestFullScreen();
        } else if (container.webkitRequestFullscreen) { // Chrome, Safari
          container.webkitRequestFullscreen();
        } else if (container.msRequestFullscreen) { // IE/Edge
          container.msRequestFullscreen();
        }
      } else {
        // 退出全屏
        if (document.exitFullscreen) {
          document.exitFullscreen();
        } else if (document.mozCancelFullScreen) {
          document.mozCancelFullScreen();
        } else if (document.webkitExitFullscreen) {
          document.webkitExitFullscreen();
        } else if (document.msExitFullscreen) {
          document.msExitFullscreen();
        }
      }
    },

    // 处理窗口大小变化
    handleResize() {
      // 根据窗口大小调整布局
      // 这里可以添加响应式调整的逻辑
    },

    // 实际执行视频加载的方法(确保已登录WVP平台)
    doLoadVideo(channel, panelIndex, panel) {
      const deviceId = channel.deviceId || channel.wvpDeviceId; // 设备国标ID
      const channelId = channel.wvpDeviceChannelId; // 通道国标ID

      if (!deviceId || !channelId) {
        panel.loading = false;
        this.$message.error("无效的设备或通道信息，无法播放");
        return;
      }

      // 使用WVP的接口获取直播流播放地址
      wvpStartPlay(deviceId, channelId)
        .then(response => {
          if (response && response.code === 0 && response.data) {
            let streamUrl = '';
            // 按照优先级选择流地址: HLS > WSS/WS-FLV > FLV
            if (response.data.hls) {
              streamUrl = response.data.hls;
            } else if (response.data.wss_flv) {
              streamUrl = response.data.wss_flv;
            } else if (response.data.ws_flv) {
              streamUrl = response.data.ws_flv;
            } else if (response.data.flv) {
              streamUrl = response.data.flv;
            } else {
              panel.loading = false;
              this.$message.error("未获取到可用的视频流地址");
              return;
            }

            panel.streamUrl = streamUrl;
            panel.loading = false;
            this.$message.success(`已加载视频流到面板 ${panelIndex + 1}`);

            // 找到对应的播放器实例并开始播放
            this.$nextTick(() => {
              const player = this.$refs[`player-${panelIndex}`];
              if (player && player[0]) {
                player[0].startInlinePlay(streamUrl);
              }
            });
          } else {
            panel.loading = false;
            this.$message.error(`加载视频失败: ${response.msg || '获取播放地址失败'}`);
          }
        }).catch(error => {
          panel.loading = false;
          this.$message.error(`加载视频失败: ${error.message || '未知错误'}`);
        });
    },

    // 查询国标设备信息
    getWvpDeviceInfo(deviceId) {
      return new Promise((resolve, reject) => {
        try {
          console.log("========== 国标设备查询详细过程 ==========");
          console.log(`输入参数: deviceId = ${deviceId}`);
          console.log(`说明: 该deviceId应该是IoT设备表中的wvp_device_id字段值`);
          console.log(`目标: 在WVP设备表中查找device_id = ${deviceId}的记录`);

          // 检查是否有效
          if (!deviceId) {
            console.error("【错误】传入的deviceId为空");
            reject(new Error("设备ID不能为空"));
            return;
          }

          // 构建查询参数
          const queryParams = { device_id: deviceId };
          console.log(`策略: 将使用device_id字段查询WVP设备表`);
          console.log(`查询参数:`, queryParams);
          console.log(`即将发送API请求: listWvpDevice(${JSON.stringify(queryParams)})`);

          // 使用列表接口查询
          console.log(`正在执行WVP设备查询...`);

          listWvpDevice(queryParams)
            .then(response => {
              console.log(`收到WVP设备表查询响应:`, response);
              console.log(`响应状态码: ${response?.code}, 消息: ${response?.msg}`);

              if (response && response.code === 200) {
                if (response.rows && response.rows.length > 0) {
                  const device = response.rows[0];
                  console.log(`查询成功! 找到WVP设备记录:`);
                  console.log(`- WVP设备表.id(主键): ${device.id}`);
                  console.log(`- WVP设备表.deviceId(国标编号): ${device.deviceId}`);
                  console.log(`- WVP设备表.name(名称): ${device.name}`);

                  // 关键验证：后端返回的记录是否与查询的ID匹配
                  console.log("【关键验证】检查后端返回数据一致性:");
                  console.log(`- 前端请求的ID: ${deviceId}`);
                  console.log(`- 后端返回的ID: ${device.deviceId}`);

                  if (device.deviceId !== deviceId) {
                    const errorMsg = "后端返回了不匹配的设备数据! 请检查WVP系统或数据库。";
                    console.error(`【严重数据不一致】${errorMsg}`);
                    reject(new Error(errorMsg));
                    return;
                  }

                  console.log(`✅ 验证通过！后端返回的设备ID与请求ID一致。`);
                  resolve(device);

                } else {
                  const errorMsg = `未在WVP中找到设备(ID: ${deviceId})`
                  console.warn(`⚠ ${errorMsg}`);
                  reject(new Error(errorMsg));
                }
              } else {
                const errorMsg = `查询WVP设备失败: ${response ? response.msg : '未知错误'}`;
                console.error(`【错误】${errorMsg}`);
                reject(new Error(errorMsg));
              }
            })
            .catch(error => {
              console.error('WVP设备查询API请求出错:', error);
              reject(error);
            });
        } catch (error) {
          console.error('【严重错误】国标设备查询过程发生未捕获的异常:', error);
          reject(error);
        }
      });
    },

    // 根据设备ID查询通道列表
    getWvpChannelsByDeviceId(deviceId) {
      return new Promise((resolve, reject) => {
        try {
          console.log("========== 国标通道查询详细过程 ==========");
          console.log(`输入参数: deviceId = ${deviceId}`);
          console.log(`说明: 该deviceId应该是WVP设备表中的id字段(主键)`);
          console.log(`目标: 在WVP通道表中查找data_device_id = ${deviceId}的记录`);

          // 检查是否有效
          if (!deviceId) {
            console.error("【错误】传入的deviceId为空");
            reject(new Error("设备ID不能为空"));
            return;
          }

          // 查看deviceId是否为纯数字
          const isNumeric = /^\d+$/.test(deviceId);
          console.log(`检查: deviceId是否为纯数字 = ${isNumeric}`);

          // 构建查询参数
          let queryParams = {};

          if (isNumeric && deviceId.length < 5) {
            console.log(`推测: deviceId=${deviceId} 是WVP设备表的主键id(数字)`);
            queryParams = { data_device_id: deviceId };
            console.log(`策略: 将使用data_device_id字段查询WVP通道表`);
          } else {
            console.log(`警告: deviceId=${deviceId} 可能不是正确的WVP设备主键id`);
            console.log(`策略: 尝试将deviceId作为国标设备编号查询`);
            // 不修改查询参数，让接口直接处理
            queryParams = { data_device_id: deviceId };
          }

          console.log(`查询参数:`, queryParams);
          console.log(`即将发送API请求: listWvpDeviceChannel(${JSON.stringify(queryParams)})`);

          console.log(`正在执行WVP通道查询...`);
          listWvpDeviceChannel(queryParams)
            .then(response => {
              console.log(`收到WVP通道查询响应:`, response);
              console.log(`响应状态码: ${response?.code}, 消息: ${response?.msg}`);

              if (response && response.code === 200) {
                if (response.rows && response.rows.length > 0) {
                  const channels = response.rows;
                  console.log(`查询成功! 找到WVP通道记录: ${channels.length}个`);

                  // 验证关系
                  const firstChannel = channels[0];
                  console.log(`验证通道与设备的关系:`);
                  console.log(`- WVP设备表主键ID = ${deviceId}`);
                  console.log(`- WVP通道表data_device_id = ${firstChannel.data_device_id}`);

                  if (String(deviceId) === String(firstChannel.data_device_id)) {
                    console.log(`✓ 验证通过！两者一致`);
                  } else {
                    console.warn(`⚠ 警告！通道与设备关系不一致，可能是WVP数据库设置错误。 (${firstChannel.data_device_id} != ${deviceId})`);
                  }

                  resolve(channels);
                } else {
                  console.warn(`⚠ 未找到WVP通道记录! 查询参数:`, queryParams);
                  console.log(`响应中rows数组为空或不存在`);

                  // 尝试用设备ID作为通道ID直接查询
                  console.log(`尝试备用查询方式...`);
                  console.log(`直接查询deviceId=${deviceId}的通道`);

                  console.log(`即将发送备用API请求: listWvpDeviceChannel({ deviceId: "${deviceId}" })`);
                  return listWvpDeviceChannel({ deviceId: deviceId })
                    .then(backupResponse => {
                      console.log(`备用查询响应:`, backupResponse);
                      console.log(`备用响应状态码: ${backupResponse?.code}, 消息: ${backupResponse?.msg}`);

                      if (backupResponse && backupResponse.code === 200 &&
                          backupResponse.rows && backupResponse.rows.length > 0) {
                        const channels = backupResponse.rows;
                        console.log(`✓ 备用查询成功! 找到WVP通道记录(通过deviceId=${deviceId}): ${channels.length}个`);
                        resolve(channels);
                      } else {
                        console.warn(`✗ 备用查询也未找到通道记录`);
                        console.log(`结论: 在WVP通道表中找不到与设备ID(${deviceId})对应的通道记录`);
                        resolve([]);
                      }
                    })
                    .catch(error => {
                      console.error(`备用查询出错:`, error);
                      console.log(`错误信息: ${error.message || '未知错误'}`);
                      console.log(`备用查询失败，返回空数组`);
                      resolve([]);
                    });
                }
              } else {
                console.error(`查询失败! 错误码: ${response ? response.code : '未知'}, 错误信息: ${response ? response.msg : '未知错误'}`);
                reject(new Error(response ? response.msg : '查询失败'));
              }
            })
            .catch(error => {
              console.error('WVP通道查询出错:', error);
              console.error(`错误信息: ${error.message || '未知错误'}`);
              console.error(`错误堆栈: ${error.stack || '无堆栈信息'}`);

              // 尝试打印错误详情
              try {
                if (error.response) {
                  console.error('错误响应数据:', error.response.data);
                  console.error('错误HTTP状态:', error.response.status);
                }
              } catch (e) {
                console.error('无法获取更多错误信息:', e);
              }

              reject(error);
            });
        } catch (error) {
          console.error('【严重错误】国标通道查询过程发生未捕获的异常:', error);
          console.error(`错误信息: ${error.message || '未知错误'}`);
          console.error(`错误堆栈: ${error.stack || '无堆栈信息'}`);
          reject(error);
        }
      });
    },

    // 获取通道类型文本描述
    getChannelTypeText(channelType) {
      if (channelType === 0) return '未知类型';
      if (channelType === 1) return '视频通道';
      if (channelType === 2) return '音频通道';
      if (channelType === 3) return '音视频复合通道';
      if (channelType === 4) return '报警通道';
      return '其他类型';
    },
  }
};
</script>

<style scoped>
.video-split-view {
  height: calc(100vh - 120px);
  display: flex;
  flex-direction: column;
  background-color: #141414;
  border-radius: 4px;
  overflow: hidden;
}

.split-view-container {
  display: flex;
  flex: 1;
  overflow: hidden;
}

/* 左侧设备列表面板 */
.channel-list-panel {
  width: 380px;
  display: flex;
  flex-direction: column;
  background-color: #1f1f1f;
  border-right: 1px solid #2c2c2c;
}

.panel-header {
  padding: 12px 15px;
  background-color: #1f1f1f;
  border-bottom: 1px solid #2c2c2c;
}

.panel-header .panel-title {
  font-size: 16px;
  font-weight: bold;
  color: #fff;
}

.panel-content {
  flex: 1;
  padding: 10px;
  overflow-y: auto;
}

/* 操作引导区域 */
.operation-guide {
  margin-bottom: 15px;
}

/* 右侧视频区域 */
.video-view-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.control-panel {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 15px;
  background-color: #1f1f1f;
  border-bottom: 1px solid #2c2c2c;
}

.left-controls, .right-controls {
  display: flex;
  align-items: center;
}

.right-controls .el-button {
  margin-left: 8px;
}

.video-container {
  flex: 1;
  display: grid;
  gap: 2px;
  padding: 2px;
  background-color: #1a1a1a;
  overflow: hidden;
}

/* 布局样式 */
.layout-1 {
  grid-template-columns: 1fr;
  grid-template-rows: 1fr;
}

.layout-4 {
  grid-template-columns: 1fr 1fr;
  grid-template-rows: 1fr 1fr;
}

.layout-9 {
  grid-template-columns: repeat(3, 1fr);
  grid-template-rows: repeat(3, 1fr);
}

.layout-16 {
  grid-template-columns: repeat(4, 1fr);
  grid-template-rows: repeat(4, 1fr);
}

.video-panel {
  position: relative;
  background-color: #0d0d0d;
  border: 1px solid #2c2c2c;
  overflow: hidden;
  transition: all 0.3s;
  display: flex;
  flex-direction: column;
  cursor: pointer;
}

.video-panel.active {
  border: 2px solid #409EFF;
  box-shadow: 0 0 10px rgba(64, 158, 255, 0.5);
}

/* 右上角删除按钮 */
.panel-close-btn {
  position: absolute;
  top: 10px;
  right: 10px;
  width: 28px;
  height: 28px;
  background-color: rgba(0, 0, 0, 0.6);
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #fff;
  cursor: pointer;
  z-index: 10;
  transition: all 0.3s;
  opacity: 0;
}

.panel-close-btn i {
  font-size: 14px;
}

.video-panel:hover .panel-close-btn {
  opacity: 1;
}

.panel-close-btn:hover {
  background-color: #f56c6c;
  transform: scale(1.1);
}

.video-wrapper {
  flex: 1;
  position: relative;
  overflow: hidden;
  background-color: #0d0d0d;
}

.video-iframe {
  width: 100%;
  height: 100%;
  border: none;
}

.panel-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 5px 10px;
  background-color: rgba(0, 0, 0, 0.7);
  color: #fff;
  font-size: 12px;
  height: 24px;
  position: relative;
}

.panel-title {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  flex: 1;
}

.panel-controls i {
  margin-left: 8px;
  cursor: pointer;
  font-size: 14px;
  transition: color 0.2s;
}

.panel-controls i:hover {
  color: #ff4d4f;
}

.panel-number {
  position: absolute;
  top: 4px;
  right: 10px;
  width: 18px;
  height: 18px;
  line-height: 18px;
  background-color: #409EFF;
  color: white;
  border-radius: 50%;
  text-align: center;
  font-size: 12px;
}

.panel-detail {
  padding: 2px 10px;
  background-color: rgba(0, 0, 0, 0.5);
  color: #aaa;
  font-size: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-top: 1px solid #2c2c2c;
}

.detail-item {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.empty-panel {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100%;
  color: #666;
  cursor: pointer;
}

.empty-panel i {
  font-size: 36px;
  margin-bottom: 10px;
}

.empty-panel p {
  margin: 0;
  font-size: 14px;
  text-align: center;
  padding: 0 10px;
}

.video-panel.active .empty-panel {
  color: #409EFF;
}

/* 表格样式定制 */
.channel-list-panel .el-table {
  background-color: #1f1f1f;
  color: #fff;
  border: 1px solid #2c2c2c;
}

.channel-list-panel .el-table th,
.channel-list-panel .el-table tr {
  background-color: #1f1f1f;
}

.channel-list-panel .el-table--striped .el-table__body tr.el-table__row--striped td {
  background-color: #262626;
}

.channel-list-panel .el-table td,
.channel-list-panel .el-table th.is-leaf {
  border-bottom: 1px solid #2c2c2c;
}

.channel-list-panel .el-table--enable-row-hover .el-table__body tr:hover>td {
  background-color: #363636;
}

/* 全屏模式样式 */
:fullscreen .video-container {
  height: 100vh;
}

:fullscreen .control-panel {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
  background-color: rgba(0, 0, 0, 0.7);
}

/* 响应式样式 */
@media screen and (max-width: 1200px) {
  .channel-list-panel {
    width: 300px;
  }
}

@media screen and (max-width: 768px) {
  .channel-list-panel {
    width: 250px;
  }

  .layout-9, .layout-16 {
    gap: 1px;
  }

  .panel-info {
    padding: 2px 5px;
    height: 20px;
    font-size: 10px;
  }

  .panel-controls i {
    font-size: 12px;
  }
}

/* 树形控件样式定制 */
.device-tree {
  background-color: #1f1f1f;
  color: #fff;
}

.device-tree .el-tree-node__content:hover {
  background-color: #363636;
}

.device-tree .el-tree-node:focus > .el-tree-node__content {
  background-color: #363636;
}

.el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content {
    background-color: #409EFF;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
